<template>
  <div class="app-container">
    <div ref="filter" class="filter-container" style="margin-bottom: unset;">
      <template>
        <el-input
          v-model="listQuery.mobile"
          size="small"
          placeholder="请填写客户手机号码"
          style="width: 200px;margin-left:5px"
          class="filter-item filter-left"
          clearable
        />
        <el-select
          v-model="listQuery.status"
          class="filter-left"
          placeholder="请选择客户状态"
          clearable
          filterable
          size="small"
        >
          <el-option v-for="item in statusOption" :label="item.label" :value="item.value"/>
        </el-select>
        <el-select
          v-model="listQuery.type"
          class="filter-left"
          placeholder="请选择客户类型"
          clearable
          filterable
          size="small"
        >
          <el-option v-for="item in typeOption" :label="item.label" :value="item.value"/>
        </el-select>
        <!--        <el-date-picker-->
        <!--          v-model="listQuery.addTime"-->
        <!--          type="datetimerange"-->
        <!--          size="small"-->
        <!--          range-separator="至"-->
        <!--          start-placeholder="开始日期"-->
        <!--          end-placeholder="结束日期">-->
        <!--        </el-date-picker>-->
        <el-button
          size="small"
          class="filter-item filter-left"
          icon="el-icon-search"
          type="primary"
          style="margin-left:5px"
          plain
          @click="search()"
        >
          搜索
        </el-button>
        <el-button
          size="small"
          class="filter-item right filter-left filter-refresh"
          icon="el-icon-refresh"
          type="primary"
          plain
          @click="refresh()"
        />
      </template>
    </div>
    <div ref="filter" class="filter-container">
      <el-button
        size="small"
        class="filter-item left"
        type="primary"
        icon="el-icon-plus"
        style="margin-left: 5px;"
        @click="addRow()"
        v-if="isMy || isIntention"
      >
        新建客户
      </el-button>
      <el-button
        size="small"
        class="filter-item left"
        type="warning"
        style="margin-left: 5px;"
        icon="el-icon-s-grid"
        @click="setCustomerGroupCollect"
        v-if="isMy || isIntention"
      >
        设置分组
      </el-button>
      <el-button
        size="small"
        class="filter-item left"
        type="danger"
        style="margin-left: 5px;"
        icon="el-icon-price-tag"
        @click="setCustomerLabelCollect"
        v-if="isMy || isIntention"
      >
        设置标签
      </el-button>
      <el-button
        size="small"
        class="filter-item left"
        type="info"
        style="margin-left: 5px;"
        icon="el-icon-paperclip"
        @click="setCustomerSourceCollect"
        v-if="isMy || isIntention"
      >
        设置来源
      </el-button>
      <el-button
        size="small"
        class="filter-item left"
        type="success"
        style="margin-left: 5px;"
        icon="el-icon-success"
        @click="setCustomerDealStatusCollect"
        v-if="isMy || isIntention"
      >
        批量更改成交状态
      </el-button>
      <el-button
        size="small"
        class="filter-item left"
        type="warning"
        style="margin-left: 5px;"
        icon="el-icon-star-on"
        @click="setCustomerIntentionCollect"
        v-if="isMy || isIntention"
      >
        批量更新意向状态
      </el-button>
      <el-button
        size="small"
        class="filter-item left"
        style="margin-left: 5px;"
        icon="el-icon-s-unfold"
        @click="setCustomerIsPrivateCollect(0)"
        v-if="isMy || isIntention"
      >
        批量移入公海
      </el-button>
      <el-button
        size="small"
        class="filter-item left"
        style="margin-left: 5px;"
        type="warning"
        icon="el-icon-upload2"
        @click="importCustomer()"
        v-if="isMy "
      >
        导入
      </el-button>
      <el-button
        size="small"
        class="filter-item left"
        style="margin-left: 5px;"
        type="warning"
        icon="el-icon-download"
        @click="openExportCustomer()"
        v-if="isMy"
      >
        导出
      </el-button>
      <el-button
        size="small"
        class="filter-item left"
        style="margin-left: 5px;"
        icon="el-icon-s-fold"
        @click="setCustomerIsPrivateCollect(1)"
        v-if="isWater"
      >
        批量认领客户
      </el-button>
    </div>
    <!---->
    <el-dialog
      title="导出客户"
      :visible.sync="exportCustomerState"
      width="425px">
      <div class="form-scrollbar" style="height: 150px">
        <div style="line-height: 150px">
          <el-radio-group v-model="exportMode">
            <el-radio :label="1">已勾选的客户导出</el-radio>
            <el-radio :label="2">搜索条件导出</el-radio>
            <el-radio :label="3">全部导出</el-radio>
          </el-radio-group>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="exportCustomerState = false">取 消</el-button>
        <el-button type="primary" @click="exportCustomer">确 定</el-button>
      </span>
    </el-dialog>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      fit
      border
      size="medium"
      :height="tableHeight"
      :header-cell-style="{background:'#F2F6FC'}"
      @selection-change="handleSelection"
      class="customer"
    >
      <el-table-column type="selection" align="center">

      </el-table-column>
      <el-table-column align="center" label="序号" width="60" type="index">
      </el-table-column>

      <!-- 公海 -->
      <template v-if="isWater">
        <el-table-column align="center" label="客户名称" prop="name" show-overflow-tooltip/>
        <el-table-column align="center" label="职称" prop="jobTitle" show-overflow-tooltip/>
        <el-table-column align="center" label="手机" prop="mobile"/>
        <el-table-column align="center" label="邮箱" prop="email"/>
        <el-table-column align="center" label="备注" prop="remarks" show-overflow-tooltip/>
        <el-table-column align="center" label="最后跟进记录" prop="followMessage" show-overflow-tooltip/>
        <el-table-column align="center" label="前负责人" prop="belongUserId">
          <template slot-scope="{row}">
            {{row.belongUser.trueName}}
          </template>
        </el-table-column>
      </template>
      <!-- 我的客户 -->
      <template v-if="isMy || isIntention">
        <el-table-column align="center" label="类型" width="80" prop="type" show-overflow-tooltip>
          <el-table-column align="center" label="来源" width="80" prop="sourceId" show-overflow-tooltip>
            <template slot-scope="{row}">
              <template v-if="row.type == 1">全球搜索</template>
              <template v-else-if="row.type == 2">数据营销</template>
              <template v-else>全球搜索</template>
              <el-divider></el-divider>
              {{row.sourceId ? row.source.name : '无'}}
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column align="center" label="分组" width="80" prop="groupId" show-overflow-tooltip>
          <template slot-scope="{row}">
            {{row.groupId ? row.group.name : '未分组'}}
          </template>
        </el-table-column>
        <el-table-column align="center" label="标签" width="80" type="index">
          <template slot-scope="{row}">
            <template v-if="row.labels">
              <template v-for="(v,k) in row.labels" style="margin-bottom: 2px">
                <el-tag
                  :style="{'background-color':v.color,'border-color':v.color}"
                  size="mini"
                  effect="dark">
                  {{ v.name }}
                </el-tag>
              </template>
            </template>
            <template v-else>无</template>
          </template>
        </el-table-column>
        <el-table-column align="center" label="客户名称" prop="name" width="100" show-overflow-tooltip>
          <el-table-column align="center" label="职称" prop="jobTitle" width="200" show-overflow-tooltip>
            <template slot-scope="{row}">
              <el-link type="primary" @click="infoRow(row.id)">{{row.name}}</el-link>
              <el-divider></el-divider>
              {{row.jobTitle ? row.jobTitle : '无'}}
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column align="center" label="手机" prop="mobile" width="200">
          <el-table-column align="center" label="邮箱" prop="email" width="200">
            <template slot-scope="{row}">
              {{row.mobile}}
              <el-divider></el-divider>
              {{row.email}}
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column align="center" label="成交状态" prop="dealStatus" width="200">
          <el-table-column align="center" label="关注度" prop="attention" width="200">
            <el-table-column align="center" label="备注" width="200" prop="remarks" show-overflow-tooltip>
              <template slot-scope="{row}">
                <template v-if="row.dealStatus == 1">
                  <i class="el-icon-success" style="color: #20b559;"></i>&nbsp;已成交
                </template>
                <template v-else>
                  <i class="el-icon-error" style="color: #f95a5a;"></i>&nbsp;未成交
                </template>
                <el-divider></el-divider>
                <el-rate
                  v-model="row.attention"
                  @change="setCustomerAttention(row.id,row.attention)"
                  :colors="colors">
                </el-rate>
                <el-divider></el-divider>
                {{row.remarks ? row.remarks : '无'}}
              </template>
            </el-table-column>
          </el-table-column>
        </el-table-column>
        <el-table-column align="center" label="负责人" prop="belongUserId" width="200" show-overflow-tooltip>
          <el-table-column align="center" label="创建人" prop="userId" width="200" show-overflow-tooltip>
            <el-table-column align="center" label="最后跟进时间" prop="followAt" width="200" show-overflow-tooltip>
              <template slot-scope="{row}">
                {{row.belongUser.trueName}}
                <el-divider></el-divider>
                {{row.user.trueName}}
                <el-divider></el-divider>
                {{row.followAt ? row.followAt : '无'}}
              </template>
            </el-table-column>
          </el-table-column>
        </el-table-column>
        <el-table-column align="center" label="获取客户时间" prop="belongUserId" show-overflow-tooltip>
          <el-table-column align="center" label="创建时间" prop="belongAt" show-overflow-tooltip>
            <el-table-column align="center" label="最后跟进记录" prop="followMessage" show-overflow-tooltip>
              <template slot-scope="{row}">
                {{row.belongAt}}
                <el-divider></el-divider>
                {{row.createdAt}}
                <el-divider></el-divider>
                {{row.followMessage ? row.followMessage : '无'}}
              </template>
            </el-table-column>
          </el-table-column>
        </el-table-column>
        <el-table-column align="center" label="更新时间" prop="updatedAt" width="150"/>

      </template>
      <el-table-column align="center" label="操作" width="240">
        <template slot-scope="{row}">
          <template v-if="isMy || isIntention">
            <el-button-group style="margin-bottom:5px">
              <el-tooltip class="item" effect="dark" content="编辑客户" placement="top-start">
                <el-button type="primary" size="mini" icon="el-icon-edit" @click="editRow(row.id)"/>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="设置分组" placement="top-start">
                <el-button type="warning" size="mini" icon="el-icon-s-grid" @click="setCustomerGroup(row.id)"/>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="设置来源" placement="top-start">
                <el-button type="info" size="mini" icon="el-icon-paperclip" @click="setCustomerSource(row.id)"/>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="设置标签" placement="top-start">
                <el-button type="danger" size="mini" icon="el-icon-price-tag" @click="setCustomerLabel(row.id)"/>
              </el-tooltip>

            </el-button-group>
            <el-button-group>
              <el-tooltip class="item" effect="dark" content="更改成交状态" placement="top-start">
                <el-button type="success" size="mini" icon="el-icon-success" @click="setCustomerDealStatus(row.id)"/>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="更改意向状态" placement="top-start">
                <el-button size="mini" type="warning" icon="el-icon-star-on" @click="setCustomerIntention(row.id)"/>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="跟进记录" placement="top-start">
                <el-button size="mini" type="danger" icon="el-icon-chat-dot-round" @click="customerFollow(row.id)"/>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="操作日志" placement="top-start">
                <el-button size="mini" type="primary" icon="el-icon-chat-line-square" @click="customerLog(row.id)"/>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="移入公海" placement="top-start">
                <el-button size="mini" icon="el-icon-s-unfold" @click="setCustomerIsPrivate(row.id,0)"/>
              </el-tooltip>
            </el-button-group>
          </template>
          <template v-if="isWater">
            <el-button-group>
              <el-tooltip class="item" effect="dark" content="认领客户" placement="top-start">
                <el-button size="mini" icon="el-icon-s-fold" @click="setCustomerIsPrivate(row.id,1)"/>
              </el-tooltip>
            </el-button-group>
          </template>
        </template>
      </el-table-column>
    </el-table>
    <Pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="fetchData"
    />
    <Group :id="collectId" :show.sync="showGroupState" @closeAction="refresh"/>
    <ChangeDealStatus :id="collectId" :show.sync="showDealState" @closeAction="refresh"/>
    <Intention :id="collectId" :show.sync="showIntentionState" @closeAction="refresh"/>
    <Label :id="collectId" :show.sync="showLabelState" @closeAction="refresh"/>
    <Source :id="collectId" :show.sync="showSourceState" @closeAction="refresh"/>
    <Edit :id="id" :show.sync="showState" @closeAction="refresh"/>
    <Drawer :id="id" :show.sync="showInfoState" @closeAction="refresh"/>
    <DialogFollow :id="id" :show.sync="showFollowState" @closeAction="refresh"/>
    <DialogLog :id="id" :show.sync="showLogState" @closeAction="refresh"/>
  </div>
</template>

<script>
import {getCustomerIds, getCustomerAllIds, getList, setAttention, SetIsPrivate} from "@/api/customer/index";
import Pagination from '@/components/Pagination';
import Group from '@/views/customer/common/group';
import Label from '@/views/customer/common/label';
import Source from '@/views/customer/common/source';
import ChangeDealStatus from '@/views/customer/common/changeDealStatus';
import Intention from '@/views/customer/common/intention';
import Edit from './edit';
import Drawer from './drawer';
import DialogFollow from './dialogFollow';
import DialogLog from './dialogLog';

export default {
  name: "CustomerIndex",
  components: {Pagination, Group, Edit, Drawer, ChangeDealStatus, Label, Intention, Source, DialogFollow, DialogLog},
  props: {
    action: {
      type: String
    },
  },
  created() {
    this.checkTab();
  },
  destroyed() {
    VUE.$off('importCallBack')
  },
  data() {
    return {
      exportMode: 1,
      exportCustomerState: false,
      isMy: false,
      isIntention: false,
      isWater: false,
      collectId: '',
      colors: ['#99A9BF', '#F7BA2A', '#FF9900'],
      clientHeight: document.documentElement.clientHeight,
      clientWidth: document.documentElement.clientWidth,
      listLoading: false,
      tableHeight: 'calc(100vh - 240px)',
      list: [],
      selection: [],
      showGroupState: false,
      showDealState: false,
      showLabelState: false,
      showIntentionState: false,
      showSourceState: false,
      showFollowState: false,
      showLogState: false,
      showState: false,
      showInfoState: false,
      id: '',
      total: 0,
      listQuery: {
        status: '',
        type: '',
        addTime: '',
        limit: 20,
        action: -1,
      },
      statusOption: [
        {label: '未成交', value: 0},
        {label: '已成交', value: 1},
        {label: '已跟进', value: 2},
        {label: '未跟进', value: 3},
      ],
      typeOption: [
        {label: '全球搜索', value: 1},
        {label: '数据营销', value: 2},
        {label: '外部导入', value: 3},
      ],
    }
  },
  mounted() {
    this.fetchData()
    window.onresize = () => {
      this.clientHeight = document.documentElement.clientHeight;
      this.clientWidth = document.documentElement.clientWidth;
    }
  },

  methods: {
    checkTab() {
      //初始化
      this.isMy = false;
      this.isIntention = false;
      this.isWater = false;

      if (this.action === 'my') {
        this.isMy = true;
        this.listQuery.action = 1;
      }//我的客户
      if (this.action === 'intention') {
        this.isIntention = true;
        this.listQuery.action = 2;
      }//意向客户
      if (this.action === 'water') {
        this.isWater = true;
        this.listQuery.action = 3;
      }//
    },
    async fetchData() {
      this.listLoading = true

      let listQuery = JSON.parse(JSON.stringify(this.listQuery))
      if (listQuery.status === '') {
        listQuery.status = -1;
      }
      const {data} = await getList(listQuery, listQuery.page, listQuery.limit)
      this.list = data.items
      this.total = data.total
      if (this.total && this.isMy) {
        this.setTableHeight(315);
      } else if (this.isMy) {
        this.setTableHeight(275);
      }
      if (this.total && (this.isIntention || this.isWater)) {
        this.setTableHeight(283);
      } else if (this.isIntention || this.isWater) {
        this.setTableHeight(242);
      }
      setTimeout(() => {
        this.listLoading = false
      }, 0.5 * 1000)
    },
    setCustomerLabel(id) {
      this.collectId = id;
      this.showLabelState = true
    },
    setCustomerSourceCollect() {
      if (this.selection.length <= 0) {
        this.$message({
          type: 'info',
          message: '请勾选需要设置来源的客户'
        })
        return false;
      }
      let ids = [];
      for (let i in this.selection) {
        ids.push(this.selection[i].id);
      }
      this.collectId = ids;
      this.showSourceState = true
    },
    setCustomerSource(id) {
      this.collectId = id;
      this.showSourceState = true
    },
    setCustomerLabelCollect() {
      if (this.selection.length <= 0) {
        this.$message({
          type: 'info',
          message: '请勾选需要设置标签的客户'
        })
        return false;
      }
      let ids = [];
      for (let i in this.selection) {
        ids.push(this.selection[i].id);
      }
      this.collectId = ids;
      this.showLabelState = true
    },
    setCustomerGroupCollect() {
      if (this.selection.length <= 0) {
        this.$message({
          type: 'info',
          message: '请勾选需要设置分组的客户'
        })
        return false;
      }
      let ids = [];
      for (let i in this.selection) {
        ids.push(this.selection[i].id);
      }
      this.collectId = ids;
      this.showGroupState = true
    },
    setCustomerGroup(id) {
      this.collectId = id;
      this.showGroupState = true
    },
    setCustomerDealStatusCollect() {
      if (this.selection.length <= 0) {
        this.$message({
          type: 'info',
          message: '请勾选需要批量更改成交状态'
        })
        return false;
      }
      let ids = [];
      for (let i in this.selection) {
        ids.push(this.selection[i].id);
      }
      this.collectId = ids;
      this.showDealState = true;
    },
    setCustomerDealStatus(id) {
      this.collectId = id;
      this.showDealState = true;
    },
    setCustomerIsPrivateRes(val = 0) {
      let msg = '';
      let title = ''
      if (val == 0) {
        title = '移入'
        msg = '确认要将该客户移入公海？';
        if (typeof this.id != 'object') {
          msg = '确认要将客户移入公海？'
        }
      } else {
        title = '认领'
        msg = '确认要认领该客户？';
        if (typeof this.id != 'object') {
          msg = '确认要认领客户？'
        }
      }

      this.$confirm(msg, '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let data = {ids: this.collectId, value: val}

        if (typeof data.ids != 'object') {
          data.ids = [data.ids]
        }
        await SetIsPrivate(data).then((res) => {
          this.$notify({
            title: '成功',
            message: `${title}成功`,
            type: 'success',
            duration: 2000
          })
          this.fetchData();
        })
      })
    },
    setCustomerIsPrivate(id, val = 0) {
      this.collectId = id;
      this.setCustomerIsPrivateRes(val)
    },
    setCustomerIsPrivateCollect(val = 0) {
      if (this.selection.length <= 0) {
        let msg = '';
        if (val == 0) {
          msg = '请勾选需要批量移入公海的客户';
        } else {
          msg = '请勾选需要批量认领的客户'
        }
        this.$message({
          type: 'info',
          message: msg
        })
        return false;
      }
      let ids = [];
      for (let i in this.selection) {
        ids.push(this.selection[i].id);
      }
      this.collectId = ids;
      this.setCustomerIsPrivateRes(val)
    },
    setCustomerIntentionCollect() {
      if (this.selection.length <= 0) {
        this.$message({
          type: 'info',
          message: '请勾选需要批量更改成交状态'
        })
        return false;
      }
      let ids = [];
      for (let i in this.selection) {
        ids.push(this.selection[i].id);
      }
      this.collectId = ids;
      this.showIntentionState = true;
    },
    setCustomerIntention(id) {
      this.collectId = id;
      this.showIntentionState = true;
    },
    refresh() {
      // 刷新重置条件
      this.listQuery = {
        status: '',
        source: '',
        addTime: '',
        action: this.listQuery.action,
      }
      this.showLogState = false;
      this.showFollowState = false;
      this.showIntentionState = false;
      this.showGroupState = false;
      this.showLabelState = false;
      this.showSourceState = false;
      this.showDealState = false;
      this.showState = false;
      this.showInfoState = false;
      this.fetchData()
    },
    search() {
      this.fetchData()
    },
    setTableHeight(height) {
      this.tableHeight = 'calc(100vh - ' + (height) + 'px)'
    },
    setCustomerAttention(id, val) {
      this.$confirm('确认要修改该客户的关注度吗？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        this.listLoading = true
        let data = {id: id, attention: val}
        await setAttention(data).then((res) => {
          this.$notify({
            title: '成功',
            message: '更新成功',
            type: 'success',
            duration: 2000
          })
          this.fetchData()
        })
      }).catch(() => {
        this.fetchData()
      })
    },
    handleSelection(val) {
      this.selection = val
    },
    addRow() {
      this.id = ''
      this.showState = true
    },
    editRow(id) {
      this.id = id
      this.showState = true
    },
    infoRow(id) {
      this.id = id
      this.showInfoState = true
    },
    customerFollow(id) {
      this.id = id
      this.showFollowState = true
    },
    customerLog(id) {
      this.id = id
      this.showLogState = true
    },
    importCustomer() {
      let _this = this;
      this.$common.ExeInvoke(function (f) {
        f.ImportClient()
      })
      this.importCallBack()
    },
    importCallBack() {
      let _this = this;
      VUE.$on('importCallBack', () => {
        _this.refresh();
      })
    },
    openExportCustomer() {
      this.exportMode = 1
      this.exportCustomerState = true;
    },
    async exportCustomer() {
      let mode = this.exportMode;
      switch (mode) {
        case 1:
          if (this.selection.length <= 0) {
            this.$message({
              type: 'info',
              message: '请勾选需要导出的客户'
            })
            return false;
          }
          let ids = [];
          for (let i in this.selection) {
            ids.push(this.selection[i].id);
          }
          let _this = this
          this.$common.ExeInvoke(function (f) {
            f.ExportClient(ids);
            _this.exportCustomerState = false;
          })
          break;
        case 2:
          let listQuery = JSON.parse(JSON.stringify(this.listQuery))
          if (listQuery.status === '') {
            listQuery.status = -1;
          }
          await getCustomerIds(listQuery).then((res) => {
            console.log(res);
            if (!res.data.length) {
              this.$message({
                type: 'warning',
                message: '未获取到客户数据'
              })
            }
            let ids = res.data
            this.$common.ExeInvoke(function (f) {
              f.ExportClient(ids);
              _this.exportCustomerState = false;
            })
          })
          break;
        case 3:
          let params = {};
          params['action'] = this.listQuery.action;
          await getCustomerAllIds(params).then((res) => {
            if (!res.data.length) {
              this.$message({
                type: 'warning',
                message: '未获取到客户数据'
              })
            }
            let ids = res.data
            this.$common.ExeInvoke(function (f) {
              f.ExportClient(ids);
              _this.exportCustomerState = false;
            })
          })
          break;
      }
    }
  }
}
</script>

<style scoped>
/deep/ label {
  font-weight: unset;
}

.customer /deep/ .el-divider--horizontal {
  margin: 5px 0 !important;
}
</style>
